package com.zj.leetcode.easy.tree;

/**
 * @program: algorithm
 * @description: 另一棵树的子树
 * 572 subtree-of-another-tree
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class SubtreeOfAnotherTree {
    public static void main(String[] args) {
        Solution solution = new SubtreeOfAnotherTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public boolean isSubtree(TreeNode root, TreeNode subRoot) {
            return find(subRoot, root);
        }

        public boolean find(TreeNode s, TreeNode t) {
            if (s == null) {
                return false;
            }
            return check(s, t) || find(s.left, t) || find(s.right, t);
        }

        public boolean check(TreeNode s, TreeNode t) {
            if (s == null && t == null) {
                return true;
            }
            if (s == null || t == null || s.val != t.val) {
                return false;
            }
            return check(s.left, t.left) && check(s.right, t.right);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}

